<template>
  <div class="app-container">
    <div style="width: 50%">
      <h3>{{ $t("warehouseEntryLang.intelligentPrint") }}</h3>
      <el-table :data="oderData" border class="mt-10" szie="mini" highlight-current-row @row-click="singleElection">
        <el-table-column
          :label="$t('warehouseEntryLang.provider')"
          prop="providerName"
          align="center"
          min-width="100"
        />
        <el-table-column
          :label="$t('harvestLang.providerChannel')"
          prop="providerChannelName"
          align="center"
          min-width="100"
        />
        <el-table-column
          :label="$t('statusLang.oneVoteForOnePiece')"
          prop="oneToOne"
          align="center"
          min-width="100"
        >
          <template slot-scope="scope">
            <el-radio v-if="scope.row.oneToOne !== 0" v-model="checked" :label="scope.row.rmOne" @input="inputChange">{{
              scope.row.oneToOne === 0 ? null : scope.row.oneToOne
            }}</el-radio>
          </template>
        </el-table-column>
        <el-table-column
          :label="
            $t('statusLang.oneVoteForMoreThanOnePiece')
          "
          prop="oneToMost"
          align="center"
          min-width="100"
        >
          <template slot-scope="scope">
            <el-radio v-if="scope.row.oneToMost !== 0" v-model="checked" :label="scope.row.rmMost" @input="inputChange">{{
              scope.row.oneToMostBox !== 0 ? scope.row.oneToMost : null
            }}</el-radio>
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="选择" width="55">
           // 添加一个多选框,控制选中与否
          单选的也可以用单选框,这样效果更明显,选择之后不能取消
          <template slot-scope="scope">
            <el-radio v-model="checked" :label="scope.row.oneToOne" @input="inputChange"
              >{{ scope.row.oneToOne }}</el-radio
            >
          </template>
        </el-table-column>
        <el-table-column align="center" label="111" width="55">
          <template slot-scope="scope">
            <el-radio v-model="checked" :label="scope.row.providerChannelId" @input="inputChange"
              >{{ scope.row.providerChannelId }}</el-radio
            >
          </template>
        </el-table-column> -->
      </el-table>
      <el-row type="flex" justify="start" style="margin-top: 10px">
        <el-button type="primary" :disabled="!checked" @click="handlePrint(row)">{{ $t("warehouseEntryLang.printPickingList") }}</el-button>
      </el-row>

      <el-dialog
        :visible="generatePicketVisible"
        :title="$t('warehouseEntryLang.printPickingList')"
        width="400px"
        @close="generatePicketClose"
      >
        <div class="m-info" style="margin-left: 20px;">
          <el-form ref="form" :model="form" label-position="top" label-width="80px" size="mini">
            <el-form-item :label="$t('warehouseEntryLang.pleaseInputQty')">
              <el-input v-model.number="form.orderQty" type="number" />
            </el-form-item>
            <el-form-item label="" prop="type">
              <el-radio-group v-model="form.type">
                <el-radio :label="1">{{ $t("warehouseEntryLang.byLocation") }}</el-radio>
                <el-radio :label="2">{{ $t("warehouseEntryLang.byTime") }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
        <div slot="footer">
          <el-button @click="generatePicketClose">{{ $t("cancel") }}</el-button>
          <el-button
            type="primary"
            :loading="reveiceSubmitLoading"
            @click="confirm"
          >{{ $t("confirm") }}</el-button>
        </div>
      </el-dialog>
      <!-- 智能套打 -->
      <vue-easy-print
        v-show="isShow"
        ref="easyPrintBox"
        table-show
        :one-page-row="onePageRow"
      >
        <div class="skuHead" style="text-align: left">
          <h2>Express</h2>
        </div>
        <div class="skuInfo" style="margin-bottom: 10px;">
          <div class="title">
            <span>Carrier Name: {{ outboundOrder.providerName }}</span>
          </div>
          <div class="title">
            <span>Service Type: {{ outboundOrder.providerChannelName }}</span>
          </div>
          <hr>
          <div class="title">
            <span>Last Mile Deilvery No.</span>
          </div>
        </div>
        <vue-barcode
          line-color="#000"
          display-value="true"
          format="CODE128"
          font="bold"
          :value="outboundOrder.siCode"
          text-align="center"
          text-position="bottom"
          text-margin="5"
          font-size="26"
          height="60"
          width="2"
          class="barCode"
        />
        <div class="skuInfo" style="">
          <div class="title">
            <span>order count: {{ outboundOrder.orderCount }}</span>
          </div>
          <div class="title">
            <span>sku count: {{ outboundOrder.skuCount }}</span>
          </div>
          <div class="title">
            <span>Storage Location: {{ outboundOrder.storageLocation }}</span>
          </div>
        </div>
      </vue-easy-print>
      <!-- 普通打印 -->
      <vue-easy-print
        v-show="isShow"
        ref="easyPrintBoxGeneral"
        table-show
        :one-page-row="onePageRow"
      >
        <div class="skuHead" style="text-align: left">
          <h2>Express</h2>
        </div>
        <div class="skuInfo" style="margin-bottom: 10px;">
          <hr>
          <div class="title">
            <span>Last Mile Deilvery No.</span>
          </div>
        </div>
        <vue-barcode
          line-color="#000"
          display-value="true"
          format="CODE128"
          font="bold"
          :value="outboundOrder.siCode"
          text-align="center"
          text-position="bottom"
          text-margin="5"
          font-size="26"
          height="60"
          width="2"
          class="barCode"
        />
        <div class="skuInfo" style="">
          <div class="title">
            <span>order count: {{ outboundOrder.orderCount }}</span>
          </div>
          <div class="title">
            <span>sku count: {{ outboundOrder.skuCount }}</span>
          </div>
          <div class="title">
            <span>Storage Location: {{ outboundOrder.storageLocation }}</span>
          </div>
        </div>
      </vue-easy-print>
    </div>
    <div style="margin-top: 100px">
      <!-- 分页查询 -->
      <h3>{{ $t("warehouseEntryLang.pool") }}</h3>
      <el-form
        ref="queryParams"
        :model="queryParams"
        size="small"
        label-suffix=":"
        label-position="right"
        label-width="120px"
      >
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-form-item>
              <template #label>
                <el-select
                  v-model="queryParams.orderType"
                  :placeholder="$t('pleaseSelect')"
                  @change="changeOrderType"
                >
                  <el-option
                    :value="-1"
                    :label="$t('outboundOrderLang.outDocNo')"
                  />
                  <el-option
                    :value="0"
                    :label="$t('outboundOrderLang.trackingNo')"
                  />
                  <el-option
                    :value="1"
                    :label="$t('outboundOrderLang.providerNo')"
                  />
                </el-select>
              </template>
              <el-input
                v-model="orderNumber"
                :placeholder="$t('pleaseEnter')"
                size="small"
                style="width: 200px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="1.5">
            <el-form-item>
              <template #label>
                <el-select
                  v-model="queryParams.dateType"
                  @change="changeDateType"
                >
                  <el-option
                    v-for="item in outboundDateOptions"
                    :key="item.value"
                    :value="item.value"
                    :label="$t(item.title)"
                  />
                </el-select>
              </template>
              <el-date-picker
                v-model="queryParams.dateTime"
                type="daterange"
                value-format="timestamp"
                :range-separator="$t('to')"
                :start-placeholder="$t('beginDate')"
                :end-placeholder="$t('endDate')"
                @change="changeDateTime"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-form-item
              :label="$t('warehouseEntryLang.provider')"
              prop="providerId"
            >
              <el-select
                v-model="queryParams.providerId"
                :placeholder="$t('warehouseEntryLang.provider')"
                style="width: 200px"
                clearable
              >
                <el-option
                  v-for="item in providerList"
                  :key="item.value"
                  :value="item.value"
                  :label="item.title"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="1.5">
            <el-form-item
              :label="$t('harvestLang.providerChannel')"
              prop="providerChannelId"
            >
              <el-select
                v-model="queryParams.providerChannelId"
                :placeholder="$t('pleaseSelect')"
                style="width: 200px"
                clearable
              >
                <el-option
                  v-for="item in providerChannelList"
                  :key="item.value"
                  :value="item.value"
                  :label="item.title"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-form-item
              :label="$t('sku')"
              prop="skuCode"
            >
              <el-input
                v-model="queryParams.skuCode"
                :placeholder="$t('pleaseEnter')"
                size="small"
                style="width: 200px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="1.5">
            <el-form-item
              :label="$t('harvestLang.customerName')"
              prop="customerId"
            >
              <el-select
                v-model="queryParams.customerId"
                :placeholder="$t('pleaseSelect')"
                style="width: 200px"
                clearable
                filterable
              >
                <el-option
                  v-for="item in customerList"
                  :key="item.value"
                  :value="item.value"
                  :label="item.title"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="1.5">
            <el-form-item
              :label="$t('outboundOrderLang.orderVoteType')"
              prop="providerChannelId"
            >
              <el-select
                v-model="queryParams.orderVoteType"
                :placeholder="$t('pleaseSelect')"
                clearable
                @change="changeOrderVoteType"
              >
                <el-option
                  :value="0"
                  :label="$t('statusLang.oneVoteForOnePiece')"
                />
                <el-option
                  :value="1"
                  :label="$t('statusLang.oneVoteForMoreThanOnePiece')"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-search"
              @click="handleQuery"
            >
              {{ $t("query") }}
            </el-button>
            <el-button
              type="primary"
              size="small"
              icon="el-icon-refresh-left"
              @click="handleReset"
            >
              {{ $t("reset") }}
            </el-button>
          </el-col>
        </el-row>
      </el-form>
      <!-- 操作栏 -->
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button type="primary" :disabled="multipleSelection.length < 1" @click="printOutboundOrder()">
            {{ $t("warehouseEntryLang.printPickingList") }}
          </el-button>
        </el-col>
      </el-row>
      <!-- 数据列表 -->
      <el-table
        ref="table"
        v-loading="loading"
        :data="tableData"
        size="mini"
        class="mt-10"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="center" min-width="55" />
        <el-table-column
          :label="$t('tableIndex')"
          type="index"
          :index="indexAdd"
          align="center"
          width="80"
        />
        <el-table-column
          :label="$t('goodsSKULang.baseSkuInfoDTO')"
          prop="providerTrackingNo,platformOrderNo,providerTrackingNo"
          align="left"
          min-width="210"
        >
          <template slot-scope="scope">
            <p>
              {{ $t("outboundOrderLang.outDocNo") + ":" }}
              <span>{{ scope.row.orderNo }}</span>
            </p>
            <p>
              {{ $t("outboundOrderLang.trackingNo") + ":" }}
              <span>{{ scope.row.trackingNo }}</span>
            </p>
            <p>
              {{ $t("outboundOrderLang.rigDocNo") + ":" }}
              <span>{{ scope.row.platformOrderNo }}</span>
            </p>
            <p>
              {{ $t("outboundOrderLang.providerNo") }}:
              <span>{{ scope.row.providerTrackingNo }}</span>
            </p>
            <p>
              {{ $t("outboundOrderLang.sku") }}:
              <span>
                <span v-for="(goods, index) in scope.row.goodsList" :key="goods.goodsId">
                  {{ goods.goodsSkuCode }}<span v-if="index < scope.row.goodsList.length - 1">, </span>
                </span>
              </span>
            </p>
            <p>
              <span v-for="(goods, index) in scope.row.goodsList" :key="'count-' + goods.goodsId">
                sku总数: {{ getSkuCount(goods.goodsSkuCode) }}<span v-if="index < scope.row.goodsList.length - 1">; </span>
              </span>
            </p>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('warehouseEntryLang.providerInfo')"
          prop="providerChannelName,providerName"
          align="left"
          min-width="160"
        >
          <template slot-scope="scope">
            <p>
              {{ $t("harvestLang.providerChannel") + ":" }}
              <span>{{ scope.row.providerChannelName }}</span>
            </p>
            <p>
              {{ $t("warehouseEntryLang.provider") + ":" }}
              <span>{{ scope.row.providerName }}</span>
            </p>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('goodsSKULang.customerCodeAndName')"
          prop="customerName,customerCode"
          align="center"
          min-width="230"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.customerCode }}【{{
              scope.row.customerName
            }}】</span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('goodsSKULang.depotCodeAndName')"
          prop="depotName,depotCode"
          align="center"
          min-width="140"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.depotCode }}【{{ scope.row.depotName }}】</span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('outboundOrderLang.orderType')"
          prop="orderVoteTypeName"
          align="center"
          min-width="120"
        >
          <!-- <template slot-scope="scope">
            <span>{{
              $t(
                "statusLang." +
                  getTitleByValue(invoicingStatusOptions, scope.row.orderType)
              )
            }}</span>
          </template> -->
        </el-table-column>
        <el-table-column
          :label="$t('outboundOrderLang.numberOfPieces')"
          prop="goodsQuantityTotal"
          align="center"
          min-width="80"
        />
        <el-table-column
          :label="$t('outboundOrderLang.countryOfDestination')"
          prop="regionName"
          min-width="150"
          align="center"
        />
        <el-table-column
          :label="$t('orderDate')"
          prop="gmtCreated"
          min-width="150"
          align="center"
        />
      </el-table>
    </div>

    <!-- 页码 -->
    <el-row type="flex" justify="end" align="middle" style="height: 60px">
      <el-pagination
        :total="total"
        layout="total,sizes,prev,pager,next,jumper"
        :page-sizes="[10, 20, 30, 50, 100, 200, 1000, 2000, 5000]"
        :current-page="queryParams.pageNo"
        :page-size="queryParams.pageSize"
        @current-change="pageNoChange"
        @size-change="handleSizeChange"
      />
    </el-row>
  </div>
</template>

<script>
import VueBarcode from 'vue-barcode'
import vueEasyPrint from 'vue-easy-print'
import { outboundDateDict, invoicingStatusDict } from '@/utils/dictData'
import { getDictOptionList, getTitleByValue } from '@/utils/dictUtils'
import {
  queryOutboundOrderPageList,
  getStatisticsOutboundOrderVoteList,
  generateOutboundOrderExpressList,
  printOutboundOrderExpressList,
  getCustomerList
} from '@/api/business/outboundManage/invoicing'
import { getProviderList } from '@/api/business/provider/provider'
import { getProviderChannelList } from '@/api/business/provider/providerChannel'
export default {
  name: 'Invoicing',
  components: { VueBarcode, vueEasyPrint },
  data() {
    return {
      multipleSelection: [],
      oderData: [],
      tableData: [],
      providerChannelList: [],
      customerList: [],
      providerList: [],
      loading: false,
      total: 0,
      orderNumber: null,
      queryParams: {
        pageNo: 1,
        pageSize: 20,
        orderType: -1,
        orderVoteType: '',
        dateType: 0,
        trackingNo: null, // 物流单号
        providerTrackingNo: null, // 物流商单号
        providerChannelId: null,
        providerId: null,
        gmtCreatedStart: null, // 下单日期
        gmtCreatedEnd: null,
        outboundTimeStart: null, // 出库日期
        outboundTimeEnd: null,
        receiveTimeStart: null, // 签收日期
        receiveTimeEnd: null,
        customerId: ''
      },
      outboundDateDict: outboundDateDict,
      invoicingStatusDict: invoicingStatusDict,
      getTitleByValue: getTitleByValue,
      templateSelection: '',
      checkList: [],
      checked: '',
      row: {},
      orderVoteType: '',
      orderVoteTypes: '',
      providerChannelId: '',
      isShow: false,
      outboundOrder: {
        siCode: '',
        storageLocation: ''
      },
      onePageRow: 5,
      invoicingStatusOptions: getDictOptionList(invoicingStatusDict), // 打单类型
      outboundDateOptions: [{
        title: 'orderDate',
        value: 0
      }], // getDictOptionList(outboundDateDict)
      generatePicketVisible: false,
      reveiceSubmitLoading: false,
      form: {
        orderQty: '',
        type: 2
      }
    }
  },
  created() {
    this.queryOutboundOrderPageList()
    this.getProviderChannelList()
    this.getProviderList()
    this.getStatisticsOutboundOrderVoteList()
    this.getCustomerList()
  },

  methods: {
    async getCustomerList() {
      const { data } = await getCustomerList({})
      this.customerList = data || []
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleTimeStamp(dateTime) {
      if (dateTime) {
        const timestamp = dateTime.map((item) => item)
        if (this.queryParams.dateType === 0) {
          this.queryParams.gmtCreatedStart = timestamp[0]
          this.queryParams.gmtCreatedEnd = timestamp[1]
        } else if (this.queryParams.dateType === 1) {
          this.queryParams.gmtOutboundStart = timestamp[0]
          this.queryParams.gmtOutboundEnd = timestamp[1]
        } else if (this.queryParams.dateType === 2) {
          this.queryParams.outboundTimeStart = timestamp[0]
          this.queryParams.outboundTimeEnd = timestamp[1]
        }
      } else {
        this.queryParams.gmtCreatedStart = null
        this.queryParams.gmtCreatedEnd = null
      }
    },
    async getStatisticsOutboundOrderVoteList() {
      this.queryParams.orderNo = undefined
      this.queryParams.trackingNo = undefined
      this.queryParams.providerTrackingNo = undefined
      if (this.queryParams.orderType === -1) {
        this.queryParams.orderNo = this.orderNumber
      } else if (this.queryParams.orderType === 0) {
        this.queryParams.trackingNo = this.orderNumber
      } else if (this.queryParams.orderType === 1) {
        this.queryParams.providerTrackingNo = this.orderNumbers
      }
      this.queryParams.orderStatus = 0
      const { data } = await getStatisticsOutboundOrderVoteList({
        ...this.queryParams
      })
      this.oderData = data?.map(item => {
        item.rmOne = Math.random()
        item.rmMost = Math.random()
        return item
      })
    },
    async getProviderChannelList() {
      const { data } = await getProviderChannelList({
        channelName: ''
      })
      this.providerChannelList = data
    },
    async getProviderList() {
      const { data } = await getProviderList({
        providerName: ''
      })
      this.providerList = data
    },
    handleQuery() {
      this.loading = true
      this.queryParams.pageNo = 1
      this.getStatisticsOutboundOrderVoteList()
      this.queryOutboundOrderPageList()
      this.loading = false
    },
    async queryOutboundOrderPageList() {
      this.queryParams.orderNo = undefined
      this.queryParams.trackingNo = undefined
      this.queryParams.providerTrackingNo = undefined
      if (this.queryParams.orderType === -1) {
        this.queryParams.orderNo = this.orderNumber
      } else if (this.queryParams.orderType === 0) {
        this.queryParams.trackingNo = this.orderNumber
      } else if (this.queryParams.orderType === 1) {
        this.queryParams.providerTrackingNo = this.orderNumbers
      }
      this.queryParams.orderStatus = 0
      const { data } = await queryOutboundOrderPageList({
        ...this.queryParams
      })
      this.tableData = data.dataList
      this.total = data.totalRowNum
    },
    async printOutboundOrder() {
      const res = await printOutboundOrderExpressList({
        orderIdList: this.multipleSelection.map(item => item.orderId)
      })

      if (res.returnCode === 10000) {
        this.outboundOrder = res.data || {}
        this.$nextTick(() => {
          this.$refs.easyPrintBoxGeneral.print()
        })
      } else {
        this.$message.error(res.returnMsg)
      }
    },
    doPrint(val) {
      var ordonnance = document.getElementById(val).contentWindow
      setTimeout(() => {
        ordonnance.print()
      }, 500)
    },
    async handlePrint() {
      this.generatePicketVisible = true
    },
    async handleReset() {
      // await this.$refs.queryParams.resetFields();
      this.queryParams = {
        pageNo: 1,
        pageSize: 20,
        orderType: -1,
        dateType: 0,
        trackingNo: null, // 物流单号
        providerTrackingNo: null, // 物流商单号
        providerChannelId: null,
        providerId: null,
        gmtCreatedStart: null, // 下单日期
        gmtCreatedEnd: null,
        outboundTimeStart: null, // 出库日期
        outboundTimeEnd: null,
        receiveTimeStart: null, // 签收日期
        receiveTimeEnd: null
      }
      this.orderNumber = null
      this.queryOutboundOrderPageList();
    },
    changeDateType(value) {
      this.handleReset()
      this.queryParams.dateType = value
    },
    changeDateTime(dateTime) {
      this.handleTimeStamp(dateTime)
    },
    changeOrderType() {
      this.orderNumber = ''
    },
    changeOrderVoteType(val) {
      this.queryParams.orderVoteType = val
    },
    pageNoChange(newPage) {
      this.queryParams.pageNo = newPage
      this.queryOutboundOrderPageList()
    },
    handleSizeChange(pageSize) {
      this.queryParams.pageSize = pageSize
      this.queryParams.pageNo = 1
      this.queryOutboundOrderPageList()
    },
    indexAdd(index) {
      const page = this.queryParams.pageNo
      const pagesize = this.queryParams.pageSize
      return index + 1 + (page - 1) * pagesize
    },
    cancel() {},
    singleElection(row) {
      this.row = row
      this.providerChannelId = row.providerChannelId
      this.templateSelection = row.oneToOne
      this.checkList = this.tableData.filter((item) => item.oneToOne === row.oneToOne)
    },
    inputChange(val) {
      if (this.row.rmOne === val) {
        this.orderVoteType = '0'
      } else {
        this.orderVoteType = '1'
      }
    },
    generatePicketClose() {
      this.generatePicketVisible = false
    },
    async confirm() {
      if (this.form.orderQty <= 0) {
        return
      }
      const res = await generateOutboundOrderExpressList({
        orderByType: 'order_time',
        orderQty: this.form.orderQty,
        orderVoteType: this.orderVoteType,
        providerChannelId: this.providerChannelId
      })

      if (res.returnCode === 10000) {
        this.getStatisticsOutboundOrderVoteList()
        this.queryOutboundOrderPageList()
        this.outboundOrder = res.data || {}
        this.$nextTick(() => {
          this.$refs.easyPrintBox.print()
        })
      } else {
        this.$message.error(res.returnMsg)
      }
    },
    // 统计同一个sku的总条数
    getSkuCount(skuCode) {
      let count = 0;
      this.tableData.forEach(row => {
        if (Array.isArray(row.goodsList)) {
          row.goodsList.forEach(goods => {
            if (goods.goodsSkuCode === skuCode) {
              count += (goods.quantity || 1);
            }
          });
        }
      });
      return count;
    }
  },
}
</script>

<style lang="scss" scoped></style>
